package com.samuel.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.samuel.blog.bean.PageBean;
import com.samuel.blog.constant.CommonConstant;
import com.samuel.blog.utils.ResponseWriteUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
 * @author kaiji
 */
public class BaseController implements Serializable {

	private static final long serialVersionUID = -956539067827730662L;

	protected static final String SUFFIX = ".html";
	
	protected static final String REDIRECT = "redirect:";
	
	protected static final String MESSAGE_PAGE = "admin/message";
	
	protected static final String LIST = "list";

	/**
	 * 配置左侧栏样式
	 * @param request
	 * 		request 访问请求域
	 * @param sidebarId 主标题id
	 * @param subSidebarId 副标题id
	 */
	protected void configCss(HttpServletRequest request, String sidebarId, String subSidebarId) {
		request.setAttribute("sidebarId", sidebarId);
		request.setAttribute("subSidebarId", subSidebarId);
	}
	
	protected void ajax(HttpServletResponse response, int status, String message) {
		JSONObject obj = new JSONObject();
		obj.put("success", status);
		obj.put("message", message);
		ResponseWriteUtils.writeJson(response, obj.toString());
	}
	
	/**
	 * 通过key 销毁session
	 * @param request
	 * 		request请求域
	 * @param key
	 * 		session的key值
	 */
	protected void destroySession(HttpServletRequest request, String key) {
		request.getSession().removeAttribute(key);
	}
	
	/**
	 * 通过key获取session存储的对象
	 * @param request	request请求域
	 * @param key	session的key值
	 * @return	session对象
	 */
	protected Object getSessionByKey(HttpServletRequest request, String key) {
		if (null == key) {
			key = CommonConstant.USER_LOGIN_SESSION_KEY;
		}
		return request.getSession().getAttribute(key);
	}
	
	/**
	 * 通过key-value在session中存储键值对
	 *
	 * @param request	request请求域
	 * @param key		session的key值
	 * @param value		存储的值
	 */
	protected void saveByKey(HttpServletRequest request, String key, Object value) {
		request.getSession().setAttribute(key, value);
	}
	
	/**
	 * pageBean 与 dataTable的数据转换格式
	 *
	 * @param pageBean	分页实体类
	 * @param pageInfo	原始分页信息
	 * @param response	返回请求域
	 */
	protected void returnTableData(PageBean pageBean, PageInfo<?> pageInfo, HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		obj.put("draw", pageBean.getDraw());
		obj.put("recordsTotal", pageInfo.getPages());
		obj.put("recordsFiltered", pageInfo.getTotal());
		obj.put("data", pageInfo.getList());
		ResponseWriteUtils.writeJson(response, obj);
	}
	
}
